import { storeIndex, storeHouse } from '@/api/store';
import { customerIndex } from '@/api/customer';
import {
  getStoreListData, setStoreList, removeStoreList,
  getStoreHouseListData, setStoreHouseList, removeStoreHouseList,
  getCurStore, setCurStore, removeCurStore
} from '@/utils/auth'
// import router, { resetRouter } from '@/router'
import moment from 'moment'

const state = {
  storeList: JSON.parse(getStoreListData() || '[]'),
  curStore: JSON.parse(getCurStore() || '[]'),
  storeHouseList: JSON.parse(getStoreHouseListData() || '[]'),
  list: []
}

const mutations = {
  SET_LIST: (state, data) => {
    state.list = data || [];
    // const obj = {
    //   data: data || [],
    //   time: moment(new Date()).format('YYYY-MM-DD HH:mm')
    // };
    // state.storeList = { ...obj };
  },
  SET_STORE: (state, data) => {
    const obj = {
      data: data || [],
      time: moment(new Date()).format('YYYY-MM-DD HH:mm')
    };
    state.storeList = { ...obj };
    setStoreList(JSON.stringify(obj))
  },
  SET_STORE_HOUSE: (state, data) => {
    const obj = {
      data: data || [],
      time: moment(new Date()).format('YYYY-MM-DD HH:mm')
    };
    state.storeHouseList = { ...obj };
    setStoreHouseList(JSON.stringify(obj))
  },
  SET_CUR_STORE: (state, data) => {
    state.curStore = data;
    setCurStore(data);
  }
}

const actions = {
  // 获取门店列表
  getCustomerList ({ commit }, data = {}) {
    return new Promise((resolve, reject) => {
      customerIndex(data).then(res => {
        const { list, count } = res.data;
        commit('SET_LIST', list)
        resolve(list)
      }).catch(error => {
        console.log('customer--customerIndex--error==', error);
        reject(error)
      })
    })
  },
  // 获取仓库列表
  getStoreHouseList ({ commit }, data = {}) {
    return new Promise((resolve, reject) => {
      storeHouse(data).then(res => {
        const { data } = res
        const list = data?.list || [];
        commit('SET_STORE_HOUSE', list)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  setCurStore ({ commit }, data = {}) {
    commit('SET_CUR_STORE', data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
